package com.levi.stream;

import com.levi.lambda.Student;

import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collector;

/**
 * @author shentong
 * @date 2022/1/12 9:28 PM
 * @description 自定义收集器，返回集合中isPass为true的元素
 * 一般情况下自带的收集器就会满足需求，如果满足不了就需要自定义收集器
 */
public class MyCollector implements Collector<Student, List<Student>, List<Student>> {

    /**
    * 该方法用于创建一个容器
    * */
    @Override
    public Supplier<List<Student>> supplier() {
        return ArrayList::new;
    }

    /**
     * 累加器  在这个方法中进行操作
     * @return
     */
    @Override
    public BiConsumer<List<Student>, Student> accumulator() {
        return ((studentList, student) -> {
            if (student.getPass()) {
                studentList.add(student);
            }
        });
    }

    /**
     * 并行操作 多线程操作结果进行合并，非多线程情况下可以不使用此方法
     * @return
     */
    @Override
    public BinaryOperator<List<Student>> combiner() {
        return null;
    }

    /**
     * 此方法为固定写法
     * @return
     */
    @Override
    public Function<List<Student>, List<Student>> finisher() {
        return Function.identity();
    }

    @Override
    public Set<Characteristics> characteristics() {
        return EnumSet.of(Characteristics.IDENTITY_FINISH,Characteristics.UNORDERED);
    }

    public static void main(String[] args) {
        List<Student> students = new ArrayList<Student>(){{
            add(new Student(1,"zhangsan","man",20,true,90));
            add(new Student(2,"zhangsan","man",20,true,80));
            add(new Student(3,"lisi","woman",20,false,30));
            add(new Student(4,"lisi","woman",20,false,40));
            add(new Student(5,"wangwu","man",25,true,95));
            add(new Student(6,"wangwu","man",25,true,90));
            add(new Student(7,"zhaoliu","woman",25,false,50));
            add(new Student(8,"zhaoliu","woman",25,false,20));
        }};
        List<Student> collect = students.stream().collect(new MyCollector());
        System.out.println(collect);
    }
}
